package cn.vconinfo.app.interceptor;

import cn.vconinfo.app.constant.DubboConstant;
import cn.vconinfo.app.utils.IpUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class TraceIdInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // generate traceId
        String traceId = this.getUUID();
        String serverIp = IpUtils.getRemoteIp(request);
        // put traceId
        MDC.put(DubboConstant.TRACE_ID, traceId);
        MDC.put(DubboConstant.SERVER_ID, serverIp);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // clear traceId
        MDC.remove(DubboConstant.TRACE_ID);
        MDC.remove(DubboConstant.SERVER_ID);
    }
    /**
     * 获取UUID
     * @return String UUID
     */
    public String getUUID(){
        String uuid = UUID.randomUUID().toString();
        //替换-字符
        return uuid.replaceAll("-", "");
    }

}
